package com.tedu._05article.controller;

import com.tedu._05article.base.response.JsonResult;
import com.tedu._05article.base.response.StatusCode;
import com.tedu._05article.mapper.ArticleMapper;
import com.tedu._05article.pojo.dto.UserArticleParam;
import com.tedu._05article.pojo.dto.UserLoginParam;
import com.tedu._05article.pojo.entity.Article;
import com.tedu._05article.pojo.entity.User;
import com.tedu._05article.pojo.vo.ArticleVO;
import com.tedu._05article.pojo.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpSession;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/v1/user")
@Validated
public class ArticleController {
    @Autowired
    private ArticleMapper articleMapper;
    @PostMapping("/login")
    @Operation(summary = "登录")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        UserVO userVO = articleMapper.login(userLoginParam);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }
    @PostMapping("/article")
    @Operation(summary = "发表文章")

    public JsonResult article(@RequestBody @Validated UserArticleParam userArticleParam ,HttpSession session){
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(user.getId());
        articleMapper.insert(article);
        return JsonResult.success();
    }
    @GetMapping("/selectByArticleId")
    @Operation(summary = "查看文章")

    public JsonResult select(@Range(min =1,max=100,message ="文章必须在1-100之间") Long id){
        ArticleVO articleVO = articleMapper.selectByArticleId(id);
        return JsonResult.success(articleVO);
    }

}
